const {as4KDotsCostChanges} = require("../db/init");
const comBase = require("./com_base_dao");

async function add(obj = {
    stock_code: '',
    user_id: 0
}) {
    console.log(obj)
    const count = await countByStockCode(obj)
    if (count > 0) {
        return -1
    }
    console.log('add', obj.stock_code)
    // 查找股票的名字
    const info = await comBase.findOne(obj.stock_code)
    console.log('info',info)
    obj.stock_name = info.stock_name
    const res = await as4KDotsCostChanges.create(obj)
    return res.id;
}

/**
 * 列出用户成本记录
 * @param user_id 用户床
 * @param offset 页码
 * @param limit 页大小
 * @returns {Promise<Model[]>}
 */
async function findList(user_id, offset = 0, limit = 10) {

    return await as4KDotsCostChanges.findAll({
        where: {
            user_id: user_id
        },
        offset: offset,
        limit: limit,
        order: [['create_time', 'DESC']],
    });
}

module.exports.findList = findList


/**
 * 查找用户指定床id 的记录
 * @param id
 * @param user_id
 * @returns {Promise<*>}
 */
async function findOne(id, user_id) {

    return await as4KDotsCostChanges.findOne({
        where: {
            id: id,
            user_id: user_id,
        }
    });
}


/**
 * 计算用户以记录的改代码的个数,做多存在一条
 * @param stock_code 股票代码
 * @param user_id 用户id
 * @returns {Promise<*>}
 */
async function countByStockCode({stock_code, user_id}) {
    console.log({stock_code, user_id})
    return await as4KDotsCostChanges.count({
        where: {
            stock_code: stock_code,
            user_id: user_id
        }
    });
}

/**
 * 更新用户成本记录
 * @param obj 成本记录数据对象
 * @param user_id 用户 id
 * @returns {Promise<*>}
 */
async function update(obj, user_id) {
    console.log('更新用户成本记录',obj,user_id)
    return await as4KDotsCostChanges.update(obj, {
        where: {
            id: obj.id,
            user_id: user_id,
        }
    });
}


async function deleteById(id,user_id) {
    return await as4KDotsCostChanges.destroy({
        where: {
            id: id,
            user_id: user_id
        }
    });
}
module.exports.deleteById = deleteById
module.exports.count = countByStockCode
module.exports.update = update
module.exports.add = add
module.exports.findOne = findOne
